import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_base/base/controller/base_controller.dart';
import 'package:flutter_base/config/app_routes.dart';
import 'package:flutter_base/http/http_export.dart';
import 'package:flutter_base/utils/loading/loading_utils.dart';
import 'package:get/get.dart';

class ForgetPasswordLogic extends BaseController {
  // 邮箱输入控制器
  final TextEditingController emailController = TextEditingController();

  // 按钮是否可点击状态
  bool isButtonEnabled = false;

  // 倒计时
  bool isCountingDown = false;
  int countdownSeconds = 60;
  Timer? _timer;

  @override
  void onInit() {
    super.onInit();
    // 监听输入变化
    emailController.addListener(_checkInputValid);
  }

  @override
  void onClose() {
    // 取消倒计时
    _timer?.cancel();
    // 移除监听
    emailController.removeListener(_checkInputValid);
    emailController.dispose();
    super.onClose();
  }

  // 检查输入是否有效
  void _checkInputValid() {
    bool valid = _isEmailValid(emailController.text.trim());
    if (valid != isButtonEnabled) {
      isButtonEnabled = valid;
      update();
    }
  }

  // 验证邮箱格式
  bool _isEmailValid(String email) {
    if (email.isEmpty) return false;
    final emailRegExp = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
    return emailRegExp.hasMatch(email);
  }

  // 发送验证码
  Future<void> sendVerificationCode() async {
    // Get.toNamed(AppRoutes.emailVerification,
    //     arguments: {'email': 'chenxu.ios93@gmail.com', 'type': 'reset'});
    // return;
    if (!isButtonEnabled || isCountingDown) return;

    String email = emailController.text.trim();

    // HttpResponse response = await HttpManager().post(
    //   API.sendVerifyCode,
    //   params: {'email': email, 'type': 'forgot'},
    //   uiType: HttpUIType.loadingAndToast,
    // );
    //
    // if (response.isSuccess) {
    //   LoadingUtils.showToast('验证码已发送到您的邮箱');
    //   _startCountdown();
    // TODO: 跳转到验证码验证页面
    Get.toNamed(AppRoutes.emailVerification,
        arguments: {'email': email, 'type': 'reset'});
    // }
  }

  // 开始倒计时
  void _startCountdown() {
    isCountingDown = true;
    countdownSeconds = 60;
    update();

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      countdownSeconds--;
      update();
      if (countdownSeconds <= 0) {
        timer.cancel();
        isCountingDown = false;
        update();
      }
    });
  }
}
